<template>
  <div class="app-container">
    <!-- 新增：招聘计划选择 -->
    <el-form label-width="120px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="选择招聘计划">
            <el-select v-model="selectedPlanId" placeholder="请选择招聘计划" clearable style="width: 100%" @change="handlePlanChange">
              <el-option
                v-for="plan in activePlans"
                :key="plan.planId"
                :label="plan.planName"
                :value="plan.planId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 刷新、折叠搜索框按钮 -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        <el-button type="primary" @click="getMyApplyList()">我的报名</el-button>
      </el-row>
    </el-form>
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="岗位编码" prop="positionCode">
        <el-input
          v-model="queryParams.positionCode"
          placeholder="请输入岗位编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位名称" prop="positionName">
        <el-input
          v-model="queryParams.positionName"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="招聘数量" prop="positionNumber">
        <el-input
          v-model="queryParams.positionNumber"
          placeholder="请输入招聘数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄限制" prop="ageLimit">
        <el-input
          v-model="queryParams.ageLimit"
          placeholder="请输入年龄限制"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示顺序" prop="positionSort">
        <el-input
          v-model="queryParams.positionSort"
          placeholder="请输入显示顺序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位性质" prop="positionNature">
        <el-input
          v-model="queryParams.positionNature"
          placeholder="请输入岗位性质"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="薪酬" prop="salary">
        <el-input
          v-model="queryParams.salary"
          placeholder="请输入薪酬"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学历要求" prop="educationaRequirements">
        <el-input
          v-model="queryParams.educationaRequirements"
          placeholder="请输入学历要求"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入位置"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职业鉴定专业" prop="major">
        <el-input
          v-model="queryParams.major"
          placeholder="请输入职业鉴定专业"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职业技能鉴定等级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入职业技能鉴定等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作经历要求" prop="workExperienceRequirements">
        <el-input
          v-model="queryParams.workExperienceRequirements"
          placeholder="请输入工作经历要求"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次编号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 带全部岗位的 Tabs -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="job-tabs">
      <el-tab-pane label="全部岗位" name="all">
        <div class="job-list" :style="{ maxHeight: '600px', overflowY: 'auto' }">
          <div v-for="job in paginatedAll" :key="job.positionId" class="job-card" @click="showJobDetail(job)">            <!-- 卡片内容 -->
            <div class="card-header">
              <span class="job-name">{{ job.positionName }}</span>
              <span class="job-code">编码：{{ job.positionCode }}</span>
            </div>
            <div class="card-body">
              <p><strong>招聘数量：</strong>{{ job.positionNumber }}人</p>
              <p><strong>薪酬：</strong>{{ job.salary }}<span>元</span></p>
              <p><strong>学历要求：</strong>{{ job.educationaRequirements }}</p>
              <p><strong>工作地点：</strong>{{ job.location }}</p>
<!--              <p><strong>批次编号：</strong>{{ job.batchNumber }}</p>-->
            </div>
            <div class="card-footer">
              <el-button size="mini" type="primary" plain icon="el-icon-guide" @click="handleApply(job)">报名</el-button>
            </div>
          </div>
        </div>
        <!-- 在 "全部岗位" 分页中 -->
        <pagination
          v-show="totalAll > 0"
          :total="totalAll"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePaginationChange"
        />
      </el-tab-pane>

      <!-- 分类岗位 Tab -->
      <el-tab-pane v-for="(group, nature) in categorizedJobs" :key="nature" :label="nature" :name="nature">
        <div class="job-list" :style="{ maxHeight: '600px', overflowY: 'auto' }">
          <div v-for="job in paginatedCategory(group)" :key="job.positionId" class="job-card" @click="showJobDetail(job)">            <!-- 卡片内容 -->
            <div class="card-header">
              <span class="job-name">{{ job.positionName }}</span>
              <span class="job-code">编码：{{ job.positionCode }}</span>
            </div>
            <div class="card-body">
              <p><strong>招聘数量：</strong>{{ job.positionNumber }}人</p>
              <p><strong>薪酬：</strong>{{ job.salary }}<span>元</span></p>
              <p><strong>学历要求：</strong>{{ job.educationaRequirements }}</p>
              <p><strong>工作地点：</strong>{{ job.location }}</p>
<!--              <p><strong>批次编号：</strong>{{ job.batchNumber }}</p>-->
            </div>
            <div class="card-footer">
              <el-button size="mini" type="primary" plain icon="el-icon-guide" @click="handleApply(job)">报名</el-button>
            </div>
          </div>
        </div>
        <!-- 在每个分类分页中 -->
        <pagination
          v-show="group.length > 0"
          :total="group.length"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePaginationChange"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 招聘岗位信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-row :gutter="20">

        <!-- 左侧：岗位信息 -->
        <el-col :span="12">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="岗位编码" prop="positionCode" class="form-item-align">
              <el-input v-model="form.positionCode" disabled placeholder="请输入岗位编码" />
            </el-form-item>
            <el-form-item label="岗位名称" prop="positionName" class="form-item-align">
              <el-input v-model="form.positionName" disabled placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="岗位性质" prop="positionNature" class="form-item-align">
              <el-input v-model="form.positionNature" disabled placeholder="请输入岗位性质" />
            </el-form-item>
            <el-form-item label="年龄限制" prop="ageLimit" class="form-item-align">
              <el-input v-model="form.ageLimit" disabled placeholder="请输入年龄限制" />
            </el-form-item>
            <el-form-item label="学历要求" prop="educationaRequirements" class="form-item-align">
              <el-input v-model="form.educationaRequirements" disabled placeholder="请输入学历要求" />
            </el-form-item>
            <el-form-item label="职业技能鉴定专业" prop="major" class="form-item-align">
              <el-input v-model="form.major" disabled placeholder="请输入职业鉴定专业"/>
            </el-form-item>
            <el-form-item label="职业技能鉴定等级" prop="level" class="form-item-align">
              <el-input v-model="form.level" disabled placeholder="请输入职业技能鉴定等级"/>
            </el-form-item>
            <el-form-item label="工作经历要求" prop="workExperienceRequirements" class="form-item-align">
              <el-input v-model="form.workExperienceRequirements" disabled placeholder="请输入工作经历要求" />
            </el-form-item>
            <el-form-item label="招聘数量" prop="positionNumber" class="form-item-align">
              <el-input v-model="form.positionNumber" disabled placeholder="请输入招聘数量" />
            </el-form-item>
            <el-form-item label="薪酬" prop="salary" class="form-item-align">
              <el-input v-model="form.salary" disabled placeholder="请输入薪酬" />
            </el-form-item>
            <el-form-item label="位置" prop="location" class="form-item-align">
              <el-input v-model="form.location" disabled placeholder="请输入位置" />
            </el-form-item>
          </el-form>
        </el-col>

        <!-- 右侧：用户信息 -->
        <el-col :span="12">
          <el-form label-width="90px" :model="userForm" class="user-info-form">
            <el-form-item label="用户名称" class="form-item-align">
              <el-input v-model="userForm.userName" disabled />
            </el-form-item>
            <el-form-item label="政治面貌" class="form-item-align">
              <el-select v-model="userForm.political" placeholder="政治面貌" disabled style="width: 100%;">
                <el-option label="党员" value="党员"></el-option>
                <el-option label="群众" value="群众"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="性别" class="form-item-align">
              <el-select v-model="userForm.sex" disabled placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="出生时间" class="form-item-align">
              <el-date-picker v-model="userForm.birthday" type="date" disabled placeholder="出生日期"
                              style="width: 100%;" value-format="yyyy-MM-dd"/>
            </el-form-item>
            <el-form-item label="文化程度" class="form-item-align">
              <el-select v-model="userForm.culture" placeholder="文化程度" disabled style="width: 100%;">
                <el-option label="小学" value="小学"></el-option>
                <el-option label="初中" value="初中"></el-option>
                <el-option label="高中" value="高中"></el-option>
                <el-option label="大专" value="大专"></el-option>
                <el-option label="本科" value="本科"></el-option>
                <el-option label="硕士及以上" value="硕士及以上"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职业技能鉴定专业" class="form-item-align">
              <el-input v-model="userForm.major" disabled />
            </el-form-item>
            <el-form-item label="职业技能鉴定等级" class="form-item-align">
              <el-input v-model="userForm.level" disabled />
            </el-form-item>
            <el-form-item label="工作时间" class="form-item-align">
              <el-date-picker v-model="userForm.workDate" type="date" disabled style="width: 100%;"/>
            </el-form-item>
            <el-form-item label="奖惩情况" class="form-item-align">
              <RewardMultiSelect v-model="userForm.rewards" disabled style="width: 100%;"></RewardMultiSelect>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报名信息对话框 -->
    <el-dialog title="我的报名信息" :visible.sync="applyDialogVisible" width="800px" append-to-body>
      <el-form :model="applyInfo" label-width="120px" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="岗位编码">
              <el-input v-model="applyInfo.positionCode" />
            </el-form-item>
            <el-form-item label="岗位名称">
              <el-input v-model="applyInfo.positionName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次编号">
              <el-input v-model="applyInfo.batchNumber" />
            </el-form-item>
            <el-form-item label="报名时间">
              <el-input v-model="applyInfo.createTime" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="applyDialogVisible = false">修改</el-button>
        <el-button @click="applyDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import { listAvailable, getAvailable, delAvailable, addAvailable, updateAvailable } from "@/api/system/available";
import { listPlan } from "@/api/system/plan"; // 引入招聘计划接口
import { getToken } from "@/utils/auth";
import { parseTime } from "@/utils";
import {getUser, getUserProfile} from "@/api/system/user";
import { EventBus } from '@/main.js';
import {addApply, getApply, getApplyByIdcardAndBatchNumber} from "@/api/system/apply";
import RewardMultiSelect from "@/components/RewardMultiSelect.vue";


export default {
  name: "Available",
  components: {RewardMultiSelect},
  data() {
    return {
      // 招聘计划相关
      selectedPlanId: null,
      allPlans: [],         // 所有招聘计划
      activePlans: [],      // 当前可选的招聘计划（报名截止时间大于当前时间）

      // 通用数据 岗位相关
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      activeTab: 'all', // 默认选中全部岗位
      availableList: [], // 所有岗位数据
      paginatedAll: [], // 分页后的全部岗位数据
      totalAll: 0, // 全部岗位总数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        positionCode: null,
        positionName: null,
        positionNumber: null,
        ageLimit: null,
        positionSort: null,
        positionNature: null,
        salary: null,
        educationaRequirements: null,
        location: null,
        major: null,
        level: null,
        workExperienceRequirements: null,
        batchNumber: null,
        status: null,
      },
      // 表单参数
      open: false,
      form: {},
      userForm: {
        userName: '',
        phonenumber: '',
        email: '',
        sex: '',
        status: ''
      },
      applyForm: {//报名表单
        userId: null,
        deptId: null,
        userName: null,
        idcard: null,
        batchNumber: null,
        positionCode: null,
        positionName: null
      },

      applyDialogVisible: false,
      applyInfo:{//查询报名信息
        positionCode: '',
        positionName: '',
        batchNumber: '',
        applyTime: ''
      },

      // 导入参数
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/system/available/importData"
      },
      rules: {
        positionCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" }
        ],
        positionName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
        positionSort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
        batchNumber: [
          { required: true, message: "批次编号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      title: ""
    };
  },
  created() {
    this.getPlans(); // 先加载招聘计划
    // this.getList();
    this.getUserInfo();
  },
  methods: {
    getApply,
    // 示例方法：获取用户信息
    getUserInfo() {
      getUserProfile().then(response => {
        this.userForm = response.data;
      });
    },
    /** 获取所有有效的招聘计划 */
    getPlans() {
      listPlan({ pageNum: 1, pageSize: 9999 }).then(response => {
        const now = new Date();
        this.allPlans = response.rows;
        this.activePlans = response.rows.filter(plan => {
          if (!plan.registrationDeadline) return false;
          const deadline = new Date(plan.registrationDeadline);
          return deadline > now;
        });
      });
    },

    // 获取我的报名信息
    getMyApplyList() {
      const idcard = this.userForm.idcard;
      const batchNumber = this.queryParams.batchNumber;
      if (!batchNumber) {
        this.$modal.msgError("请先选择招聘计划");
        return;
      }
      const formdata = {idcard: idcard, batchNumber: batchNumber};
      console.log("身份信息："+ idcard, "批次编号："+ batchNumber);

      // 调用接口查询报名信息
      getApplyByIdcardAndBatchNumber(formdata).then(response => {
        console.log("报名信息："+ response);

        if (response.data) {
          this.applyInfo = response.data; // 取第一条记录

          // // 设置报名信息并显示对话框
          // this.applyInfo = {
          //   positionCode: applyData.positionCode || '',
          //   positionName: applyData.positionName || '',
          //   batchNumber: applyData.batchNumber || '',
          //   applyTime: parseTime(applyData.createTime) || ''
          // };
          this.applyDialogVisible = true;
        } else {
          this.$modal.msg("当前未查询到报名信息");
        }
      }).catch(error => {
        this.$modal.msgError("查询报名信息失败");
        console.error("获取报名信息失败:", error);
      });
    },

    /** 处理招聘计划选择变化 */
    handlePlanChange(planId) {
      if (!planId) {
        this.availableList = [];
        this.updatePaginatedAll();
        return;
      }

      const selectedPlan = this.allPlans.find(p => p.planId === planId);
      if (selectedPlan) {
        // 筛选岗位列表中与所选招聘计划批次号相同的岗位
        this.queryParams.batchNumber = selectedPlan.batchNumber;
        this.handleQuery();
      }
    },
    /** 查询招聘岗位信息列表 */
    getList() {
      this.loading = true;
      listAvailable(this.queryParams).then(response => {
        this.availableList = response.rows;
        // console.log("availableList:"+ this.availableList.length);
        console.log("availableList:");
        this.total = response.total;
        this.loading = false;
        this.updatePaginatedAll(); // 初始化分页数据
      });
    },

    // 切换 Tab 时更新分页
    handleTabClick(tab) {
      this.queryParams.pageNum = 1; // 切换 tab 时重置为第一页
      this.$nextTick(() => {
        if (tab.name === 'all') {
          this.updatePaginatedAll(); // 更新全部岗位数据
        }
      });
    },
    // 新增：处理分页变化
    handlePaginationChange() {
      this.$nextTick(() => {
        if (this.activeTab === 'all') {
          this.updatePaginatedAll();
        }
      });
    },

    // 更新全部岗位分页数据
    updatePaginatedAll() {
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const end = start + this.queryParams.pageSize;
      this.paginatedAll = this.availableList.slice(start, end);
      // this.totalAll = this.availableList.size();
      // console.log('更新全部岗位分页数据:' + this.totalAll);
    },


    // 分类岗位分页
    paginatedCategory(jobs) {
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const end = start + this.queryParams.pageSize;
      return jobs.slice(start, end);
    },



    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        positionId: null,
        positionCode: null,
        positionName: null,
        positionNumber: null,
        ageLimit: null,
        positionSort: null,
        positionNature: null,
        salary: null,
        educationaRequirements: null,
        location: null,
        major: null,
        level: null,
        workExperienceRequirements: null,
        batchNumber: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 报名按钮操作 */
    handleApply(row) {
      // const positionIds = row.positionId || this.ids;
      // this.$modal.confirm('是否确认删除招聘岗位信息编号为"' + positionIds + '"的数据项？').then(function() {
      //   return delAvailable(positionIds);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {});
      this.showJobDetail(row);
    },

    // 显示岗位详情对话框
    showJobDetail(job) {
      this.form = { ...job }; // 深拷贝岗位信息到 form
      this.open = true; // 打开对话框
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 填充报名信息
          this.applyForm.positionId = this.form.positionId;
          this.applyForm.userId = this.userForm.userId; // 假设用户信息中包含 userId
          this.applyForm.deptId = this.userForm.deptId; // 假设用户信息中包含 deptId
          this.applyForm.userName = this.userForm.userName; // 假设用户信息中包含 userName
          this.applyForm.idcard = this.userForm.idcard; // 假设用户信息中包含 idcard
          this.applyForm.batchNumber = this.form.batchNumber; // 假设岗位信息中包含 batchNumber
          this.applyForm.positionCode = this.form.positionCode; // 假设岗位信息中包含 positionCode
          this.applyForm.positionName = this.form.positionName; // 假设岗位信息中包含 positionName
          this.applyForm.batchNumber = this.form.batchNumber; // 假设岗位信息中包含 batchNumber

          // 调用 addApply 接口
          addApply(this.applyForm)
            .then(response => {
              this.$modal.msgSuccess("报名成功");
              this.open = false; // 关闭对话框
            })
            .catch(error => {
              this.$modal.msgError("报名失败，请重试");
              console.error("报名失败:", error);
            });
        }
      });
    },


  },
  computed: {
    categorizedJobs() {
      const result = {};
      this.availableList.forEach(job => {
        const key = job.positionNature || '未知';
        if (!result[key]) {
          result[key] = [];
        }
        result[key].push(job);
      });
      return result;
    }
  }
};
</script>

<style scoped>
.form-item-align ::v-deep .el-form-item__content,
.form-item-align ::v-deep .el-form-item__label {
  display: flex;
  align-items: center;
  height: 36px;
  line-height: 20px;
  margin-bottom: 0;
}
.form-item-align ::v-deep .el-form-item__label {
  padding-right: 10px;
}
.job-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
}

.job-card {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: calc(25% - 15px);
  padding: 15px;
  transition: all 0.3s ease;
}

.job-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.15);
}

@media (max-width: 1200px) {
  .job-card {
    width: calc(33.33% - 15px);
  }
}

@media (max-width: 992px) {
  .job-card {
    width: calc(50% - 15px);
  }
}

@media (max-width: 768px) {
  .job-card {
    width: 100%;
  }
}
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.card-footer .el-button {
  padding: 5px 10px;
  font-size: 12px;
}

.card-footer .el-button:hover {
  background-color: #409eff;
  color: #fff;
}

.card-footer .el-button.is-disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

.card-footer .el-button.is-disabled:hover {
  background-color: #f5f7fa;
}

</style>
